/*
 * Copyright (c) 2003, 2004 Ulrich Hilger, http://dev.uhilger.de, all rights reserved.
 *
 * Published under the terms and conditions of the Apache License 2.0,
 * see http://www.apache.org/licenses/LICENSE-2.0
 */

package de.uhilger.app.ui;

import javax.swing.JFrame;
import java.awt.HeadlessException;
import de.uhilger.app.Application;
import de.uhilger.app.action.ExitAction;
import de.uhilger.app.DefaultApplication;
import java.awt.event.WindowEvent;
import java.awt.AWTEvent;
import de.uhilger.app.MenuApplication;
import java.util.logging.Level;

/**
 * A frame to be used as main application frame if none is present in
 * an application the subclasses the Light Development Application package</p>
 *
 * @author Ulrich Hilger, <a href="http://dev.uhilger.de" target="_blank">http://dev.uhilger.de</a>
 * @author Published under the terms and conditions of
 * the <a href="http://www.apache.org/licenses/LICENSE-2.0" target="_blank">Apache License 2.0</a>
 *
 * @version 2, February 12, 2004
 */

public class MainFrame extends JFrame {

  /**
   * constructor
   * @param title the title String for this frame
   * @throws HeadlessException
   */
  public MainFrame(Application owner, String title) throws HeadlessException {
    this.owner = owner;
    enableEvents(AWTEvent.WINDOW_EVENT_MASK); // deviate window close events accordingly
    setSize(400, 200);
    setTitle(title);
    buildMenu();
  }

  protected void buildMenu() {
    if(owner instanceof MenuApplication) {
      setJMenuBar(((MenuApplication) owner).createMenubar(MenuApplication.RB_KEY_APP_MENUBAR));
    }
  }

  /**
   * this method deviates a WindowEvent attempting to close the main frame
   * (i.e. to exit the application) to this application's exit action. This way
   * it is ensured, that all actions attempting to exit the applciation
   * are handled in the same way.
   *
   * <p>Be sure to only call super.processWindowEvent(e) when the applcation may terminate.</p>
   *
   * @param e  the WindowEvent that led to this method call
   */
  @Override
  protected void processWindowEvent(WindowEvent e) {
    if (e.getID() == WindowEvent.WINDOW_CLOSING) {
      ExitAction a = (ExitAction) owner.getAction(DefaultApplication.ACTION_EXIT_APP);
      a.actionPerformed(null);
    }
    else {
      super.processWindowEvent(e); // this should only be called, when the app may terminate
    }
  }
  
  public Application getApplication() {
    return owner;
  }

  /** the application this frame belongs to */
  private Application owner;

}
